package com.cn.dream_order_server.util;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

	public static final String DATE_PATTERN = "yyyy-MM-dd";




	//date        如果为Null，则为当前时间
	//days        加减天数
	//ncludeTime 是否包括时分秒,true表示包含
	public static Date dateAdd(Date date, int days, boolean includeTime) throws ParseException {
		if (date == null) {
			date = new Date();
		}
		if (!includeTime) {
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_PATTERN);
			date = sdf.parse(sdf.format(date));
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}

	//获取后一天的时间
	public static Date getAfterDay(Date date)  {
		if (date == null) {
			date = new Date();
		}
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_PATTERN);
		try {
			date=sdf.parse(sdf.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, 1);
		return cal.getTime();
	}

	//获取前一天的时间
	public static Date getBeforeDay(Date date)  {
		if (date == null) {
			date = new Date();
		}
		//设置时间格式
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_PATTERN);
		try {
			date=sdf.parse(sdf.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, -1);
		return cal.getTime();
	}

	//字符串解析成时间对象
	public static Date dateParse(String dateTimeString, String pattern) {
		if (StringUtils.isBlank(pattern)) {
			pattern = DateUtils.DATE_PATTERN;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		Date date = null;
		try {
			date=sdf.parse(dateTimeString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}


}